package com.lrs.java.j2se_base.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


public class ThreadStatusTest {


	public static void main(String[] args) throws Exception {
		System.out.println("main thread start ...");	
		
		ThreadStatusTest statusTest = new ThreadStatusTest();
		
//		statusTest.testThreadStatus();
		
		statusTest.testSyncStatus();
		
		
	}
	
	private void testThreadStatus() throws Exception {
		Thread t = new Thread(new SleepRunner());
		t.start();
		
		Thread.sleep(500);
		
		System.out.println("thread status " + t.getState());	//sleep() 线程status为TIMED_WAITING
	}
	
	private void testSyncStatus() throws Exception {
		Runnable runner = new SyncRunner(new ConcurrentResource());
		
		Thread t1 = new Thread(runner);
		t1.setName("t1");
		
		Thread t2 = new Thread(runner);
		t2.setName("t2");
		
		t1.start();
		Thread.sleep(100);	//确保让线程1先执行
		t2.start();
		Thread.sleep(500);	//确保线程2当前正处于等待同步锁

		//线程由于synchronized锁机制产生阻塞，此时状态为BLOCKED
		//线程由于ConcurrentLock锁产生阻塞，此时状态为WAITING
		System.out.println("thread status " + t2.getState());	
	
		for(int i=0; i<10; i++) {
			Thread.sleep(4200);
			System.out.println("t1 status " + t1.getState());	//调用condition.await()后，线程状态为WAITING
			System.out.println("t2 status " + t2.getState());	//线程2因为在sleep中状态为TIMED_WAITING
		}
		
	}
}

class SleepRunner implements Runnable {
	@Override
	public void run() {
		System.out.println("thread start...");
		
		try {
			System.out.println("thread sleep before ...");
			
			Thread.sleep(1000);
			System.out.println("thread sleep after ...");
			
		} catch (InterruptedException e) {
			System.out.println("thread interrupt occur...");
			e.printStackTrace();
		} finally {
			System.out.println("thread finally ...");
		}
		
	}
}

class SyncRunner implements Runnable {
	private ConcurrentResource resource;
	
	public SyncRunner(ConcurrentResource resource) {
		this.resource = resource;
	}
	
	@Override
	public void run() {
		resource.print(Thread.currentThread().getName());
	}
	
}

class ConcurrentResource {
	private ReentrantLock lock = new ReentrantLock();
	private Condition sufficientId = lock.newCondition();
	
	
	private int id;
	
	public /*synchronized*/ void print(String name) {
		
		while(!Thread.currentThread().isInterrupted()) {	
			try {
				lock.lock();
				
				if(name.equals("t2")) {
					id--;
					sufficientId.signalAll();
				}
				
				try {
					while(id > 1)
						sufficientId.await();
					
					id++;
				
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					System.out.println(name + " thread interrupt occur..." );
				}
				
				System.out.println(name + toString());
			} finally {
				lock.unlock();
			}
		}
		
	}
	
	public String toString() {
		return " resource : " + id;
	}
	
}



